import C from './constant'
import { getUserInfoByCode, getUserInfoByUnionId } from './../api/userInfo.js'
import { useUserInfo } from './../stores/userInfo.js'
import io from 'socket.io-client'
import moment from 'moment'
import { getWeChatSignature } from './../api/wx.js'

export let ws = null
let eventList = []

// 判断是否是微信浏览器
export function is_weixin(){
   var ua = navigator.userAgent.toLowerCase();
   if(ua.match(/MicroMessenger/i)=="micromessenger") {
       return true;
   } else {
       return false;
   }
}

export function getUrl() {
  let userAgent = navigator.userAgent;
  if (userAgent.includes("iPhone") || userAgent.includes("iPad")) {
      sessionStorage.setItem("originUrl", location.href); // 用于ios分享
  }
}

export function getBaseInfos() {
  let wxCode = ''
  if (is_weixin()) {
    getUrl()
    const code = getUrlParam("code"); // 截取路径中的code
    if (code == null || code === "") {
        let url = "";
        let userAgent = navigator.userAgent;
        if (userAgent.includes("iPhone") || userAgent.includes("iPad")) {
            url = sessionStorage.getItem("originUrl");
        } else {
            url = window.location.href;
        }
        window.location.href =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + C.appId + "&redirect_uri=" +
            encodeURIComponent('https://www.test.miaixyt.com/auth.html?backUrl=' + url) +
            "&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect";
    }

    if (code != "" && code != null) {
        wxCode = code;
        // getOpenid(code)
    }
  }
}

export async function getUserInfo(code) {
  let res = await getUserInfoByCode(code)
  if (res && res.result && res.result.union_id) {
    sessionStorage.setItem('token', res.result.token)
    sessionStorage.setItem('unionId', res.result.union_id)
    useUserInfo().setToken(res.result.token)
    useUserInfo().setUnionId(res.result.union_id)
    return res.result.union_id
  }
}

// 获取url参数
export function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg); //匹配目标参数

  if (r != null) return unescape(r[2]);
  return null; //返回参数值
}

// socket加入聊天室
export function joinRoom(roomId) {
  // 加入房间
  if (ws) {
    ws.emit('USER_JOIN_ROOM', {
      room_id: roomId,
      token: sessionStorage.getItem('token'),
      platform: 'H5'
    })
  } else {
    eventList.push({
      event: joinRoom,
      params: roomId
    })
  }
}

// socket离开聊天室
export function leaveRoom(roomId) {
  // 加入房间
  ws && ws.emit('USER_LEAVE_ROOM', {
    room_id: roomId,
    token: sessionStorage.getItem('token'),
    platform: 'H5'
  })
}

// 添加事件
export function addEvent(event, params) {
  eventList.push({
    event: event,
    params: params
  })
}

// socket初始化
export function initWebSocket() {
  if (ws) {
    return
  }
  ws = io(C.url.ws, {
    reconnectionDelay: 5000,
    reconnectionDelayMax: 5000,
    reconnectionAttempts: 5,
    reconnection: true,
    withCredentials: false,
    path: '/socket.io'
  })
  ws.on('connect', () => {
    console.log('连接成功', ws)
    // 加入系统级房间号
    ws.emit('USER_JOIN_ROOM', {
      room_id: 'SYSTEM_ROOM_ID',
      token: sessionStorage.getItem('token'),
      platform: 'H5'
    })
  })
  ws.on('connect_error', () => {
    console.log('connect_error', arguments)
  })
  ws.on('disconnect', reason => {
    console.log('disconnect:', reason)
  })
  ws.on('SYSTEM_ERROR', data => {
    console.log('SYSTEM_ERROR', data)
  })
  return ws
}

let minMessage = 1
let messageNum = 0
export function getMessageTime(time, base) {
  // 时间间隔内至少显示五条数据，
  // 多余5条，且时间在5分钟之内，则在时间间隔内全部显示
  if (time) {
    let baseTime = new Date(base).getTime() - new Date(time).getTime()
    if (messageNum < minMessage) {
      messageNum++
      return ''
    }
    if (baseTime > 300000) {
      messageNum = 0
      return moment(time).format('MM-DD HH:mm')
    } if (baseTime < -300000) {
      messageNum = 0
      return moment(time).format('MM-DD HH:mm')
    } else {
      return ''
    }
  } else {
    return ''
  }
}

export async function share(config) {
  const res = await getWeChatSignature()
  wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: res.result.appId, // 必填，公众号的唯一标识
    timestamp: res.result.timestamp, // 必填，生成签名的时间戳
    nonceStr: res.result.nonceStr, // 必填，生成签名的随机串
    signature: res.result.signature,// 必填，签名，见附录1
    jsApiList: ['onMenuShareAppMessage', 'updateAppMessageShareData']
  });
  wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
    wx.onMenuShareAppMessage(config)
  });
}